package main

import (
	"fmt"
	"strconv"
)

func main() {
	l := strToLink("12345")
	l = removeNthFromEnd(l, 2)
	fmt.Println(l)
}

type ListNode struct {
	Val  int
	Next *ListNode
}

func (l *ListNode) String() string {
	lnode := l
	str := ""
	for lnode != nil {
		str += strconv.Itoa(lnode.Val)
		lnode = lnode.Next
	}
	return str
}

func removeNthFromEnd(head *ListNode, n int) *ListNode {

	if head == nil {
		return nil
	}

	m := make(map[int]int)

	other := head
	for i := 0; other != nil; i++ {
		m[i] = other.Val
		other = other.Next
	}

	root := &ListNode{} // a new empty link
	other = root
	for i := 0; i < len(m); i++ {
		if i != len(m)-n {
			temp := &ListNode{m[i], nil}
			other.Next = temp
			other = other.Next
		}
	}

	return root.Next
}

func strToLink(str string) *ListNode {
	root := ListNode{0, nil}
	other := &root // 定义一个指针，指向第一个节点

	for i := 0; i < len(str); i++ {
		v2, _ := strconv.Atoi(string(str[i]))
		tmp := ListNode{v2, nil} // 创建临时节点
		other.Next = &tmp        // 首节点的next 指向临时节点
		other = &tmp             // other 向后移动一格
	}
	return root.Next

}
